<?php

namespace app\agent\controller;

use app\admin\service\AgentBalanceLog;
use app\agent\model\Agent as AgentModel;
use app\agent\validate\Agent as AgentValidate;
use app\common\facade\auth\Auth;
use app\model\Agent as Model;
use app\model\AgentServiceConfig;
use app\model\ChannelServDiscount;
use app\model\ServiceSub;
use app\Request;
use think\facade\Db;
use app\common\model\Export;
use app\model\Template;


class User extends Controller
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 用户信息.
     */
    public function info()
    {
        $info = Db::name('agent')
            ->where('id', $this->agent['id'])
            ->find();
        unset($info['password']);

        $basicRole = [
            [
                'permissionId' => 'user',
                'permissionName' => '基本信息',
            ],
            [
                'permissionId' => 'set',
                'permissionName' => '系统设置',
            ],
            [
                'permissionId' => 'balance',
                'permissionName' => '资金明细',
            ],
            // v2.3.3新需求 提现申请 不根据结算方式控制 直接显示
            [
                'permissionId' => 'withdraw',
                'permissionName' => '提现申请',
            ],
            [
                'permissionId' => 'customer_service',
                'permissionName' => '客服管理',
            ],
        ];
        $agentServiceConfig = new AgentServiceConfig();

        $serviceConfigs = $agentServiceConfig->getAllServOrHistory();//查询包含有历史订单的服务

        $permissionList = [
            PRODUCT_MOBILE_SERV => [
                'permissionId' => 'mobile',
                'permissionName' => '话费订单',
            ],
            PRODUCT_OIL_SERV => [
                'permissionId' => 'oil',
                'permissionName' => '滴滴加油',
            ],
            PRODUCT_COUPON_SERV => [
                'permissionId' => 'coupon',
                'permissionName' => '会员卡券订单',
            ],
//            PRODUCT_MEAL_SERV => [
//                'permissionId' => 'takeout',
//                'permissionName' => '外卖',
//            ],
            PRODUCT_FILM_SERV => [
                'permissionId' => 'movie',
                'permissionName' => '电影订单',
            ],
//            PRODUCT_METUAN_SERV => [
//                'permissionId' => 'takeout',
//                'permissionName' => '美团到店',
//            ],
//            PRODUCT_OILCARD_SERV => [
//                'permissionId' => 'oil-card',
//                'permissionName' => '油卡',
//            ],
//            PRODUCT_POWER_SERV => [
//                'permissionId' => 'power',
//                'permissionName' => '电费',
//            ],
            PRODUCT_TRAVEL_OIL_SERV => [
                'permissionId' => 'travel-oil',
                'permissionName' => '出行/加油',
            ],
            PRODUCT_AROUND_SHOP_SERV => [
                'permissionId' => 'around-shop',
                'permissionName' => '周边游',
            ],
            PRODUCT_FOOD_SHOP_SERV => [
                'permissionId' => 'food-shop',
                'permissionName' => '连锁餐饮',
            ],
            PRODUCT_ELE_SERV => [
                'permissionId' => 'takeout',
                'permissionName' => '饿了么外卖',
            ],
            PRODUCT_SECKILL_SERV => [
                'permissionId' => 'takeout',
                'permissionName' => '外卖',
            ],
            PRODUCT_MEITUAN_TAKEOUT_SERV => [
                'permissionId' => 'takeout',
                'permissionName' => '外卖',
            ],
            PRODUCT_MOBILE_CPS_SERV => [
                'permissionId' => 'cps-mobile',
                'permissionName' => 'CPS话费',
            ],
        ];

        $hasOrder = false;
        $cpsOrder = false;
        //外卖系统
        $takeout = false;

        $order = array_keys($permissionList);
        foreach ($serviceConfigs as $serv_type => $serv_name) {
            /** @var AgentServiceConfig $agentServiceConfigOne */
            $agentServiceConfigOne = AgentServiceConfig::query()->where('agent_id',Auth::agentId())->where('serv_type', $serv_type)->find();

            $income_type = !empty($agentServiceConfigOne) ? $agentServiceConfigOne->income_type : AgentServiceConfig::INCOME_TYPE_REBATE;

            if (in_array($serv_type, [PRODUCT_MEITUAN_TAKEOUT_SERV])) {

                if ($income_type == AgentServiceConfig::INCOME_TYPE_SELF){
                    $basicRole[] = [
                        'permissionId' => 'set_meituan_pub',
                        'permissionName' => '美团联盟配置',
                    ];
                }
                $takeout = true;
            }

            if (in_array($serv_type, [PRODUCT_METUAN_SERV, PRODUCT_SECKILL_SERV])) {

                if ($income_type == AgentServiceConfig::INCOME_TYPE_SELF){
                    $basicRole[] = [
                        'permissionId' => 'set_meituan_union',
                        'permissionName' => '美团分销联盟配置',
                    ];
                }

                $takeout = true;
            }
            //统计报表-----话费充值成功率
            if (in_array($serv_type, [PRODUCT_MOBILE_SERV])) {
                $basicRole[] = [
                    'permissionId' => 'call_charge_success_rate',
                    'permissionName' => '话费充值成功率',
                ];
                //$statistical = true;
            }

            //品牌权益
            if (in_array($serv_type, [PRODUCT_COUPON_SERV])) {
                $basicRole[] = [
                    'permissionId' => 'coupon_brand',
                    'permissionName' => '权益品牌',
                ];
                $basicRole[] = [
                    'permissionId' => 'coupon_brand_page_setting',
                    'permissionName' => '页面设置',
                ];
            }
            if (empty($permissionList[$serv_type])) {
                continue;
            }
            if (in_array($serv_type, $order)) {
                $hasOrder = true;
            }
            $basicRole[] = $permissionList[$serv_type];
        }

        /**
         * 之前的代理 是预付的&只代理了话费一个服务的显示老的财务对账单，否则显示新的
         */
        if ($serviceConfigs) {
            if (count($serviceConfigs) == 1 && current(array_keys($serviceConfigs)) == PRODUCT_MOBILE_SERV && $info['settle_type'] == SETTLE_TYPE_PREPAY) {
                //旧的财务对账单权限控制
                $basicRole[] = [
                    'permissionId' => 'old_financial_statement',
                    'permissionName' => '财务对账单',
                ];
            } else {
                //新的v2.4.0版本后的财务对账单权限控制
                $basicRole[] = [
                    'permissionId' => 'new_financial_statement',
                    'permissionName' => '财务对账单',
                ];
            }
        }

        //权益品牌
        /*if ($this->checkServtype('/topup/quanyi/index')) {
            $basicRole[] = [
                'permissionId' => 'coupon_brand',
                'permissionName' => '权益品牌',
            ];
            $basicRole[] = [
                'permissionId' => 'coupon_brand_page_setting',
                'permissionName' => '页面设置',
            ];
        }*/
        //本地生活
        /*if ($this->checkServtype('/topup/discount/index')) {
            $basicRole[] = [
                'permissionId' => 'discount',
                'permissionName' => '本地生活',
            ];
            $basicRole[] = [
                'permissionId' => 'discount_page_setting',
                'permissionName' => '页面设置',
            ];
        }*/
        if ($takeout) {
            $basicRole[] = [
                'permissionId' => 'takeout',
                'permissionName' => '外卖配置',
            ];
            $basicRole[] = [
                'permissionId' => 'takeout_page_setting',
                'permissionName' => '页面配置',
            ];
        }

        if ($hasOrder) {
            $basicRole[] = [
                'permissionId' => 'order',
                'permissionName' => '订单管理',
            ];
        }

        if ($hasOrder || $cpsOrder) {
            $basicRole[] = [
                'permissionId' => 'channel',
                'permissionName' => '渠道管理',
            ];
        }

        // 返佣模式
//        $profit = [
//            [
//                'permissionId' => 'withdraw',
//                'permissionName' => '提现申请',
//            ],
//        ];

        // 预充模式
        $prepay = [
            [
                'permissionId' => 'recharge',
                'permissionName' => '充值预付',
            ],
            [
                'permissionId' => 'wechat',
                'permissionName' => '公众号',
            ],
            [
                'permissionId' => 'wxpay',
                'permissionName' => '微信支付',
            ],
        ];

        $permissions = [];
        switch ($info['settle_type']) {
            case SETTLE_TYPE_PROFIT:
//                $permissions = array_merge($basicRole, $profit);
                $permissions = $basicRole;
                break;
            case SETTLE_TYPE_PREPAY:
                $permissions = array_merge($basicRole, $prepay);
                break;
            default:
                break;
        }
        $info['role'] = [
            'permissions' => $permissions,
        ];
        return success('操作成功', $info);
    }

    public function checkServtype($template_url)
    {
        $flag = true;
        $template_serv_type = (new Template())->getServType($template_url);
        $real_serv = (new ChannelServDiscount())->getRealServ('', Auth::agentId(), $template_url);
        sort($real_serv);
        foreach ($template_serv_type as $serv_type) {
            if (!in_array($serv_type,$real_serv)) {
                $flag = false;
                break;
            }
        }
        return $flag;
    }

    /**
     * 已开通产品列表
     */
    public function productList()
    {
        $list = Db::name('agent_service_config')
            ->where('agent_id', $this->agent['id'])
            ->where('status', 1)
            ->order('serv_type asc')
            ->select()
            ->toArray();

        $now = time();
        foreach ($list as $k => $v) {
            $list[$k]['name'] = PRODUCT_SERV_TYPE[$v['serv_type']]['name'] ?? '';
            $list[$k]['is_expired'] = 0;
            if (in_array($v['serv_type'], [4, 6]) && $v['income_type'] == AgentServiceConfig::INCOME_TYPE_SELF) {
                $list[$k]['time_end'] = date('Y-m-d', $v['time_end']);
                if ($v['time_end'] < $now) {
                    $list[$k]['is_expired'] = 1;
                }
            }
        }

        return success('操作成功', $list);
    }


    /**
     * 产品服务与开通过产生订单的服务
     */
    public function getAllProductOrHistory()
    {
        $obj = new AgentServiceConfig();

        $servs = $obj->getAllServOrHistory();

        return success('', $servs);

    }

    /**
     * @api {GET} /agent/user/balanceFlowList 资金明细
     */
    public function balanceFlowList(Request $request)
    {
        if (!$request->param('list_type')) {
            return fail('非法参数');
        }


        $agentBalanceLog = new AgentBalanceLog;
        $listType = $request->param('list_type');

        if ($this->agent['settle_type'] === SETTLE_TYPE_PROFIT && $listType == 'serv_payout') { // 返佣
            $listType = 'serv_commiss';
            /*} elseif ($this->agent['settle_type'] === SETTLE_TYPE_PREPAY && $listType == 'serv_commiss') { // 预付
                $listType = 'serv_payout';*/
        }

        $list = $agentBalanceLog->agentIdBalanceTypeLog($this->agent['id'], $request->all(), $listType);

        $count = $agentBalanceLog->agentIdBalanceTypeLog($this->agent['id'], $request->all(), $listType, 2);

        if ($request->param('is_export')) {
            // 导出 excel
            $res = [];
            $title = ['变动类型', '变动前余额', '变动金额', '变动后余额', '备注', '变动时间'];
            $filenameMap = [
                'serv_payout' => '预付扣款',
                'recharge' => '充值记录',
                'serv_commiss' => '佣金明细',
                'withdraw' => '提现记录',
            ];
            foreach ($list as $v) {
                $res[] = [
                    $agentBalanceLog->getTypeNameById($v['type']),
                    fen2yuan($v['old_balance']) . '',
                    fen2yuan($v['amount']) . '',
                    fen2yuan($v['new_balance']) . '',
                    $v['remark'],
                    $v['created_at'],
                ];
            }
            unset($list);
            $export = new Export;
            $name = $filenameMap[$request->param('list_type')] ?? '资金明细';
            return $export->downloadExcel($title, $res, $name);
        }

        $list['agent'] = [
            'balance' => $this->agent['balance'],
            'profit_balance' => $this->agent['profit_balance'],
            'settle_type' => intval($this->agent['settle_type']),
            'count' => $count,
        ];
        $list['list_type'] = $listType;

        return success('', $list);
    }

    /**
     * 修改密码
     */
    public function updatePassword()
    {
        $data = input('post.');
        $validate = new AgentValidate();
        if (!$validate->scene('updatePassword')->check($data)) {
            return fail($validate->getError());
        }
        $model = new AgentModel();
        $data['agent_id'] = $this->agent['id'];

        return $model->updatePassword($data);
    }

    /**
     * 上传头像.
     */
    public function uploadAvatar()
    {
        $model = new AgentModel();

        return $model->uploadAvatar($this->agent['id']);
    }

    /**
     * @api {POST} /agent/user/modifyBase 代理商基础信息修改
     * @apiDescription 代理商基础信息修改
     * @apiName agentUserModifyBase
     * @apiGroup Admin2_0_agent
     * @apiParam {String} company_name 公司名称
     * @apiParam {String} mobile 手机号
     * @apiParam {String} wexin 微信号
     * @apiParam {String} alipay 支付宝账号
     * @apiParam {String} ali_real_name 支付宝真实姓名
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function modifyBase(Request $request)
    {
        $rules = [
            'verify_code' => 'require',
            'company_name' => 'require',
            'mobile' => 'require|mobile',
            'weixin' => 'require',
            'alipay' => 'require',
            'ali_real_name' => 'require|chs',
        ];
        $messages = [
            'verify_code.require' => '请输入验证码',
            'mobile.mobile' => '请输入正确手机号',
            'mobile.require' => '请输入手机号',
            'company_name.require' => '请输入公司名称',
            'weixin.require' => '请输入微信号',
            'alipay.require' => '请输入支付宝号',
            'ali_real_name.require' => '请输入支付宝真实姓名',
            'ali_real_name.chs' => '请输入中文格式姓名',
        ];
        $param = $request->only(array_keys($rules));
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }

        // 短信验证码
        $cacheKey = 'agentBaseModify' . $param['mobile'];
        if (cache($cacheKey) != $param['verify_code']) {
            return fail('验证码错误');
        }
        unset($param['verify_code']);

        // 名字校验
        $res = Model::where('id', '<>', $this->agent['id'])->where('company_name', $param['company_name'])->field('id')->find();
        if ($res) {
            return fail('公司名称已经存在');
        }
        // 手机号校验
        $res = Model::where('id', '<>', $this->agent['id'])->where('mobile', $param['mobile'])->field('id')->find();
        if ($res) {
            return fail('手机号已经存在');
        }

        Model::where('id', $this->agent['id'])->save($param);

        return success();
    }

    /**
     * @api {POST} /agent/user/cOrderShowUpdate 订单显示开关
     * @apiDescription 前端用户即可查看自己的订单
     * @apiName agentUserCOrderShowUpdate
     * @apiGroup Admin2_0_agent
     * @apiParam {Number=1,2} order_show 是否显示
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function cOrderShowUpdate(Request $request)
    {
        $rules = [
            'order_show' => 'require|in:1,2',
        ];
        $messages = [
            'require' => '请选择',
            'in' => '非法取值',
        ];
        $param = $request->only(array_keys($rules));
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }

        if (!Model::where('id', $this->agent['id'])->save(['corder_show' => $request['order_show']])) {
            return fail();
        }

        return success();
    }

    /**
     * @api {POST} /agent/user/getCheckCode 发送验证码
     * @apiDescription 发送验证码
     * @apiName agentUserGetCheckCode
     * @apiGroup Admin2_0_agent
     * @apiParam {String} mobile 手机号
     * @apiParam {String} from 来源
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function getCheckCode(Request $request)
    {
        $rules = [
            'mobile' => 'require',
            'from' => 'require',
        ];
        $messages = [
            'require' => '请填写手机号',
        ];

        $param = $request->only(array_keys($rules));
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }

        $data = [];
        $cacheKey = $param['from'] . $param['mobile'];
        if (cache($cacheKey)) {
            if ('local' == config('app.app_env')) {
                $data['code'] = cache($cacheKey);
            }

            return fail('已经发送过了', 0, $data);
        }

        $code = mt_rand(35601, 99999);
        $res = sendSms('呆萌价代理商验证码：' . $code . '，5分钟内有效', $param['mobile']);
        if ($res['code']) {
            return fail($res['message']);
        }

        cache($cacheKey, $code, 300);
        if ('local' == config('app.app_env')) {
            $data['code'] = $code;
        }

        return success('验证发送成功，请查收!!', $data);
    }
}
